import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { ApiException } from '@main/common/exceptions/api.exception';
import SysLabelTemplate from '@main/entities/service/admin/sys/sys-label-template.entity';
import { Like, Repository } from 'typeorm';
import { SysOperationLogService } from '../operationLog/operationLog.service';

@Injectable()
export class SysLabelTemplateService {
  constructor(
    @InjectRepository(SysLabelTemplate)
    private labelTemplateRepository: Repository<SysLabelTemplate>,
    private operationLogService: SysOperationLogService, 
  ) {}

  /**
   * 分页查询标签模板列表
   */
  async page(data) {
    const { pageSize, pageNum, entity = {} } = data
    const { tempName } = entity
    return await this.labelTemplateRepository.findAndCount({
      where: {
        tempName: Like(`%${tempName}%`),
        isDelete: 0,
      },
      order: {
        updateTime: 'DESC',
      },
      take: pageSize,
      skip: (pageNum - 1) * pageSize,
    })
  }

  /**
   * 添加标签模板
   */
  async add(data, user, mac, ip, syncHostSqlite) {
    const databaseOperationLogList = [];
    const { nickName, userName } = user || {}
    const labelTemplate = await this.labelTemplateRepository.insert({
      ...data,
      createName: nickName,
      createUserName: userName,
      updateName: nickName,
      updateUserName: userName,
    })
    databaseOperationLogList.push({
      type: 'add',
      dataType: 'obj',
      database: 'SysLabelTemplate',
      checkOnlyKeyList: [],
      data: labelTemplate,
      whereObj: null,
      remark: `SysLabelTemplate表新增数据`,
    });
    await this.operationLogService.add(
      {
        type: 'add',
        msg: `标签模板新增标签模板`,
        databaseOperationLogList,
        remark: `新增标签模板${data.tempName}`,
        mac,
        ip,
        syncHostSqlite: isNaN(Number(syncHostSqlite)) ? 0 : Number(syncHostSqlite),
      },
      user
    );
  }

  /**
   * 更新标签模板
   */
  async update(data, user, mac, ip, syncHostSqlite) {
    const databaseOperationLogList = [];
    const { nickName, userName } = user || {}
    const { id, tempName, tempDetail, tempInfo, isDefault, isDelete } = data || {}
    await this.labelTemplateRepository.update(
      { id },
      {
        tempName,
        tempDetail,
        tempInfo,
        isDefault,
        isDelete,
        updateName: nickName,
        updateUserName: userName,
      },
    )
    databaseOperationLogList.push({
      type: 'update',
      dataType: 'obj',
      database: 'SysLabelTemplate',
      checkOnlyKeyList: [],
      data: {
        tempName,
        tempDetail,
        tempInfo,
        isDefault,
        isDelete,
        updateName: nickName,
        updateUserName: userName,
      },
      whereObj: { id },
      remark: `SysLabelTemplate表更新标签模板信息`,
    });
    await this.operationLogService.add(
      {
        type: 'update',
        msg: `标签模板更新标签模板`,
        databaseOperationLogList,
        remark: `更新标签模板${data.tempName}`,
        mac,
        ip,
        syncHostSqlite: isNaN(Number(syncHostSqlite)) ? 0 : Number(syncHostSqlite),
      },
      user
    );
  }

  /**
   * 删除标签模板
   */
  async delete({ id },user, mac, ip, syncHostSqlite) {
    const databaseOperationLogList = [];
    const result = await this.info({ id })
    if (result.isDefault === 1)
      throw new ApiException(10023)

    await this.labelTemplateRepository.update(
      { id },
      { isDelete: 1 },
    )
    databaseOperationLogList.push({
      type: 'delete',
      dataType: 'array',
      database: 'SysLabelTemplate',
      checkOnlyKeyList: [],
      data: null,
      whereObj: { id },
      remark: `SysLabelTemplate表删除标签模板`,
    });
    await this.operationLogService.add(
      {
        type: 'delete',
        msg: `标签模板模块删除标签模板`,
        databaseOperationLogList,
        remark: `删除标签模板`,
        mac,
        ip,
        syncHostSqlite: isNaN(Number(syncHostSqlite)) ? 0 : Number(syncHostSqlite),
      },
      user
    );
  }

  /**
   * 查询当前默认模板
   */
  async getDefault() {
    return await this.labelTemplateRepository.findOne({ where: { isDefault: 1 } })
  }

  /**
   * 设置默认模板
   */
  async setDefault({ id }, user) {
    const { nickName, userName } = user || {}
    const currentDefault = await this.getDefault()
    if (currentDefault) {
      await this.labelTemplateRepository.update(
        { id: currentDefault.id },
        {
          isDefault: 0,
        },
      )
    }
    await this.labelTemplateRepository.update(
      { id },
      {
        isDefault: 1,
        updateName: nickName,
        updateUserName: userName,
      },
    )
  }

  /**
   * 根据id获取标签模板详情
   */
  async info({ id }) {
    return await this.labelTemplateRepository.findOne({ where: { id } })
  }

  /**
   * 判断当前模板名称是否已存在
   */
  async isExistKey(tempName: string) {
    const result = await this.labelTemplateRepository.findOne({ where: { tempName, isDelete: 0 } })
    if (result)
      throw new ApiException(10022)
  }
}
